package com.qar.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qar.annotations.myRedis;
import com.qar.mapper.TUserMapper;
import com.qar.domain.TUser;
import com.qar.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author qar
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-05-13 20:32:57
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TUserMapper userMapper;

    public static final String CACHE_KEY_USER = "user:";




    @Override
    public Boolean postUser(TUser user) {
        boolean a=false;

        //将数据保存数据库
         a = save(user);
        if(a){
            //插入数据成功后将数据查出来
            TUser tUser = userMapper.selectById(user.getId());
            //将数据保存到redis中
            String key=CACHE_KEY_USER+user.getId();
            redisTemplate.opsForValue().set(key,tUser);

        }

        return a;
    }


/*

    //版本1:硬编码写
    @Override
    public TUser getUserById(Integer id) {


        //缓存key
        String key=CACHE_KEY_USER+id;
        //从缓存中查找数据
         TUser tUser= (TUser) redisTemplate.opsForValue().get(key);
         //当redis没有数据就冲数据库查找
         if(tUser==null){
             //查询数据库
             tUser = userMapper.selectById(id);
             //将数据保存到redis中
             if(tUser!=null){
                 redisTemplate.opsForValue().set(key,tUser);
             }
         }

        return tUser;
    }
*/



//版本2:热拔插AOP+反射+Redis+自定义缓存标签

    @myRedis(keyPrefix = "user",matchValue = "#id")
    @Override
    public TUser getUserById(Integer id) {

        return userMapper.selectById(id);
    }




}




